//
//  AFnetworkProxyManager.swift
//  OneDay
//
//  Created by xicheng on 16/11/14.
//  Copyright © 2016年 xicheng. All rights reserved.
//

import UIKit
import AFNetworking



class AFnetworkProxyManager:NSObject, NetworkProxyProtocol {
  
  
  static let sharedInstance = AFnetworkProxyManager()
  
  private override init(){
    
  }
  
  func handlerNetworkTask(task: NetworkTask,AndSuccess successBlock:((ResponseProxy)->Void)? ,AndError errorBlock:((Error)->Void)?)->AnyObject? {
    
    var targetTask:URLSessionDataTask? = nil
    
    let manager = AFHTTPSessionManager()
    manager.responseSerializer.acceptableContentTypes =  ["text/html","text/plain","application/json"]
    if let head = task.networkParameter?.headers  {
      for ( key, value ) in head {
        manager.requestSerializer.setValue(value, forHTTPHeaderField: key)
      }
    }
    // 兼容 Alamofire
    switch (task.method) {
      
    case .GET:
      
      targetTask =  manager.get(task.httpUrl, parameters: task.networkParameter?.params, progress: nil, success: { (httpTask, response) in
        
        successBlock?(ResponseProxy.proxyResponse(response))
        
        }, failure: { (httpTask, error) in
          errorBlock?(error)
      })
      
      break
    case .POST:
      targetTask =  manager.post(task.httpUrl, parameters: task.networkParameter?.params, progress: nil, success: { (httpTask, response) in
        successBlock?(ResponseProxy.proxyResponse(response))
        }, failure: { (httpTask, error) in
          errorBlock?(error)
      })
      break
      
    case .PUT:
      targetTask =  manager.put(task.httpUrl, parameters: task.networkParameter?.params, success: { (httpTask, response) in
        successBlock?(ResponseProxy.proxyResponse(response))
        }, failure: { (httpTask, error) in
          errorBlock?(error)
      })
      break
      
    case .DELETE:
      targetTask =  manager.delete(task.httpUrl, parameters: task.networkParameter?.params, success: { (httpTask, response) in
        successBlock?(ResponseProxy.proxyResponse(response))
        }, failure: { (httpTask, error) in
          errorBlock?(error)
      })
      break
    default:
      targetTask =  manager.post(task.httpUrl, parameters: task.networkParameter?.params, progress: nil, success: { (httpTask, response) in
        successBlock?(ResponseProxy.proxyResponse(response))
        }, failure: { (httpTask, error) in
          errorBlock?(error)
      })
      
      break
    }
    return targetTask
  }
  
  fileprivate func handlerSuccessResult(_ task:NetworkTask, httpTask:URLSessionDataTask?,response:Any?){
    
  }
  
  fileprivate func handlerErrorResult(task t:NetworkTask,error e:Error){
    
  }
}
